import React, {Component} from 'react';

import dispatcher from 'lib/dispatcher';

export default class Resizable extends Component {

  constructor(props, context) {
    super(props, context);

    this.actionHandler = this.actionHandler.bind(this);
    this.listener = this.listener.bind(this);
  }

  actionHandler(isForce) {
    if (!this.container) {
      return;
    }

    let currentWidth = this.container.offsetWidth;
    let currentHeight = this.container.offsetHeight;

    if (isForce || currentWidth !== this.originalWidth || currentHeight !== this.originalHeight) {
      window.removeEventListener('resize',this.actionHandler);
      setTimeout(()=>{
        try {
          if (this.props.onResize) {
            this.props.onResize({
              width:currentWidth,
              height:currentHeight
            }, {
              width:this.originalWidth,
              height:this.originalHeight
            });
            [this.originalWidth,this.originalHeight]=[currentWidth,currentHeight];
          }
        } finally {
          window.addEventListener('resize',this.actionHandler);
        }
      }, 0);
    }
  }

  listener(payload) {
    if (payload.$type === this.props.id) {
      this.actionHandler(true);
    }
  }

  componentDidMount() {
    this.container = this.refs.container;
    window.addEventListener('resize',this.actionHandler);
    if (this.props.useLoadFire) {
      setTimeout(()=>this.actionHandler(), 0);
    }
    this.__register = dispatcher.register(this.listener);
  }

  componentWillReceiveProps(nextProps) {
    this.actionHandler(false);
  }

  componentWillUnmount() {
    this.container = null;
    dispatcher.unregister(this.__register);
    this.__register = null;
    window.removeEventListener('resize',this.actionHandler);
  }

  render() {
    return (
      <div key={this.props.id} ref="container" className={this.props.className} style={this.props.style}>
        {this.props.children}
      </div>
    );
  }
}

Resizable.defaultProps = {
  id:null,
  className:'',
  style:{},
  onResize:null, // (current,original)=>console.log(current, original)
  useLoadFire: true
}
